package biz.ws.ws;

import api.common.result.Result;
import com.alibaba.fastjson.JSON;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

/**
 * @创建人 xiaojiancheng
 * @时间 2020/1/31
 * @描述 $k$
 */
public class WsUtils {

    public static void close(Channel channel) {
        close(channel,new Result().msg("close"));
    }

    public static void close(Channel channel, Result result) {
        channel
                .writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(result)))
                .addListener(ChannelFutureListener.CLOSE);
    }

    public static ChannelFuture write(Channel channel,Message msg){
        if(channel.isActive()){
            return channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(new Result().data(msg))));
        }
        return null;
    }

    public static ChannelFuture write(Channel channel,Result r){
        if(channel.isActive()){
            return channel.writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(r)));
        }
        return null;
    }
}
